<template>
  <div class="map-container">
    <div ref="indexMap" id="indexMap"></div>
    <!-- 搜索按钮 -->
    <el-button :icon="Search" circle class="search-btn" @click="toggleSearch" />
    <!-- 检索条件 -->
    <div class="search-form-container" v-show="isShowSearch">
      <el-form
        :inline="true"
        :model="formInline"
        label-position="right"
        class="search-form"
      >
        <el-form-item label="行政区:">
          <el-select
            v-model="formInline.xzqdm"
            placeholder="请选择行政区"
            clearable
          >
            <el-option
              v-for="(item, index) in xzqdmList"
              :key="index"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="关键字:">
          <el-input
            v-model.trim="formInline.text"
            placeholder="请输入房屋编号、姓名、地址"
          ></el-input>
        </el-form-item>
      </el-form>
      <div class="search-action">
        <div class="action-btn">
          <el-button type="primary" size="small" @click="reset">重置</el-button>
          <el-button type="primary" size="small" @click="search"
            >搜索</el-button
          >
        </div>
      </div>
    </div>
    <!-- 查询列表按钮 -->
    <el-button
      :icon="Operation"
      class="search-list-btn"
      size="mini"
      @click="openSearchList"
    />
    <!-- 查询列表 -->
    <SearchList
      ref="SearchListRef"
      :isShowSearchList="isShowSearchList"
      :tableData="tableData"
      :total="total"
      @flyToTb="flyToTb"
      @getTbList="getTbList"
      @openDetailFn="openDetailFn"
    />
    <!-- 详情列表按钮  isShowDetailListBtn-->
    <el-button
      v-if="false"
      :icon="Comment"
      class="detail-list-btn"
      size="mini"
      @click="openDetailList"
    />
    <!-- 详情列表 -->
    <DetailList
      ref="detailList"
      :isShowDetailList="isShowDetailList"
      :tableData="tableData"
      :zcList="zcList"
      :jcList="jcList"
      :xzList="xzList"
      :qjList="qjList"
      :sjList="sjList"
      :zcTotal="zcTotal"
      :jcTotal="jcTotal"
      :xzTotal="xzTotal"
      :qjTotal="qjTotal"
      :sjTotal="sjTotal"
      @_getZcList="_getZcList"
      @_getJcList="_getJcList"
      @_getXzList="_getXzList"
      @_getQjList="_getQjList"
      @_getSjList="_getSjList"
      @_getZcInfo="_getZcInfo"
      @_getJcInfo="_getJcInfo"
      @_getXzInfo="_getXzInfo"
      @_getQjInfo="_getQjInfo"
      @_getSjInfo="_getSjInfo"
      @openDetailList="openDetailList"
    />
    <!-- 详情信息按钮  isShowDetailInfoBtn-->
    <el-button
      v-if="false"
      :icon="Comment"
      class="detail-info-btn"
      size="mini"
      @click="openDetailInfo"
    />
    <!-- 详情信息 -->
    <DetailInfo
      :isShowDetailList="isShowDetailInfo"
      :currentTab="currentTab"
      :houseInfo="houseInfo"
      :yhInfo="yhInfo"
      @openDetailInfo="openDetailInfo"
    />
    <el-button
      v-if="true"
      :icon="Back"
      class="detail-back-btn"
      size="mini"
      @click="backFn"
    />
    <!-- 地图底图切换 -->
    <div class="action">
      <el-dropdown placement="left">
        <div class="el-dropdown-link">
          <el-icon class="el-icon-back"></el-icon
          ><span style="font-size: 14px">切换底图</span>
        </div>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item @click="mapSwitch('img')"
              >影像底图</el-dropdown-item
            >
            <el-dropdown-item @click="mapSwitch('vec')"
              >矢量底图</el-dropdown-item
            >
            <el-dropdown-item @click="mapSwitch('chun')"
              >纯净底图</el-dropdown-item
            >
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>
  </div>
</template>

<script setup>
import {
  onMounted,
  ref,
  reactive,
  watch,
  onBeforeUnmount,
  onBeforeMount,
  createApp,
  h,
} from 'vue'
import { useRoute,useRouter } from 'vue-router'
import bbox from '@turf/bbox'
import { baseUrl } from '@/config'
// mapbox 相关
import mapboxgl from 'mapbox-gl'
import 'mapbox-gl/dist/mapbox-gl.css'
import '@mapbox/mapbox-gl-geocoder/dist/mapbox-gl-geocoder.css'
// element 相关
import ElementPlus from 'element-plus'
import { Search, Operation, Comment ,Back} from '@element-plus/icons-vue'
// 自定义组件
import SearchList from './components/searchList.vue' // 搜索左侧列表
import DetailList from './components/detailList.vue' // 详情列表
import DetailInfo from './components/detailInfo.vue' // 详情信息
import pop from './components/pop.vue' // 气泡
// 接口引入
import {
  getZcList,
  getJcList,
  getXzList,
  getQjList,
  getSjList,
  getZcInfo,
  getJcInfo,
  getXzInfo,
  getQjInfo,
  getSjInfo,
  getFwList,
  xzqList,
} from '@/api/index.js'
const route = useRoute()
const router = useRouter()
/***********************  左侧搜索 + 列表 + 气泡 start  **************************/
// 检索条件
let formInline = reactive({
  text: '',
  xzqdm: '',
})
// 行政区划列表
const xzqdmList = ref([])
const isShowSearch = ref(false) // 是否显示搜索框
const isShowSearchList = ref(false) // 是否显示搜索列表
const SearchListRef = ref(null) // 左侧列表 dom
const tableData = ref([]) // 用于存储左侧表格数据
const total = ref(0) // 左侧表格总数
// 获取行政区列表
const _xzqList = async () => {
  let params = {
    id: '110000',
  }
  let res = await xzqList(params)
  if (res?.data?.data) {
    let list = res?.data?.data
    xzqdmList.value = list.map((item) => ({
      name: item.regionName,
      value: item.regionCode,
    }))
  }
}
// 搜索切换
const toggleSearch = () => {
  isShowSearch.value = !isShowSearch.value
}
// 重置
const reset = () => {
  formInline.xzqdm = ''
  formInline.text = ''
}
// 搜索按钮
const search = async () => {
  getTbList()
  // 清除北京矢量数据
  clearBeiJingCityFn()
  // 加载北京矢量数据
  loadBeiJingCityFn()
  // 四至范围定位
  fourRange()
}
const fourRange = async () => {
  // 获取 GeoJSON 数据
  const geojson = await fetchGeoJSONData()
  if (geojson) {
    // 计算边界框
    // const bounds = calculateBounds(geojson)

    const bounds = calculateBounds(JSON.parse(geojson))
    // 定位到中心区
    if (bounds && bounds.length === 4) {
      map.value.fitBounds(bounds, {
        padding: 50, // 可选：添加内边距
        maxZoom: 14, // 可选：限制最大缩放级别
      })
    }
  }
}
// 获取 GeoJSON 数据
const fetchGeoJSONData = async () => {
  let code = '110000'
  if (formInline.xzqdm === '') {
    code = '110000'
  } else {
    code = formInline.xzqdm
  }
  try {
    //  `https://geo.datav.aliyun.com/areas_v3/bound/${code}.json`
    //  `${baseUrl}api/v1/house/getjson?code=${code}`
    const response = await fetch(`${baseUrl}api/v1/house/getjson?code=${code}`)
    if (!response.ok) {
      throw new Error('Failed to fetch GeoJSON data')
    }
    const geojson = await response.json()
    return geojson
  } catch (error) {
    console.error('Error fetching GeoJSON data:', error)
    return null
  }
}
// 计算边界框
const calculateBounds = (geojson) => {
  // 计算边界框
  const bounds = bbox(geojson) // [minLng, minLat, maxLng, maxLat]
  return bounds
}
// 列表切换
const openSearchList = () => {
  isShowSearchList.value = !isShowSearchList.value
}
// 获取左侧列表
const getTbList = async () => {
  let params = {
    text: formInline.text,
    xzqdm: formInline.xzqdm,
    pageindex: SearchListRef.value.currentPage,
    limit: SearchListRef.value.currentSize,
  }
  let res = await getFwList(params)
  if (res?.data?.data?.items) {
    let list = res?.data?.data?.items
    list.forEach((item, index) => {
      item.index = ++index
    })
    tableData.value = list
    total.value = res?.data?.data?.total
    if (tableData.value.length > 0) {
      isShowSearchList.value = true
    }
  }
}
// 定位
const flyCoordinates = ref([]) // 定位过去 当前图斑高亮的范围
const flyZoom = ref(20) // 飞行级别
const currentId = ref('') // 定位过去 当前图斑的  id
// 列表定位到图斑
const flyToTb = async (value) => {
  flyCoordinates.value = value.flyCoordinates
  map.value.flyTo({
    center: flyCoordinates.value,
    zoom: flyZoom.value, // 放大级别
  })

  // 设置当前图斑 ID
  currentId.value = value.row.fwbh || '18fe63e7-61b7-4c2a-b491-6d67b1a4a941'
  // 更新气泡数据
  popShowData.value = value.row
  // 移除旧的气泡及其关闭事件
  if (popup.value) {
    popup.value.remove()
    popup.value = null
  }
  // 初始化新气泡
  await initPopup()

  // 先设置高亮
  await initLight()
}
// 重置图斑高亮
const resetHighlight = () => {
  if (map.value) {
    // 重置 fill-outline-color 为默认值
    map.value.setPaintProperty(
      'vectorLayer',
      'fill-outline-color',
      'rgb(255,255,0)'
    )
    // 重置 fill-color 为默认值
    map.value.setPaintProperty('vectorLayer', 'fill-color', 'transparent')
  }
}
// 初始化图斑高亮
const initLight = () => {
  let id = currentId.value
  map.value.setPaintProperty('vectorLayer', 'fill-outline-color', [
    'case',
    ['==', ['get', 'fwbh'], id],
    'red',
    'rgb(255,255,0)',
  ])
  map.value.setPaintProperty('vectorLayer', 'fill-color', [
    'case',
    ['==', ['get', 'fwbh'], id],
    'red',
    // ["get", "fill-color"],
    'transparent',
  ])
}
// 气泡
const popup = ref(null)
const popShowData = ref({}) // 接收气泡的数据
// 初始化 气泡
const initPopup = () => {
  let value = popShowData.value
  const instance = mountDomFn(value)
  popup.value = new mapboxgl.Popup({ closeOnClick: false })
    .setLngLat(flyCoordinates.value) // 默认的经纬度
    .setDOMContent(instance.$el)
    .addTo(map.value)
  // 监听气泡的关闭事件
  popup.value.on('close', () => {
    // 关闭 记录列表、记录详情
    isShowDetailList.value = false
    isShowDetailListBtn.value = false
    isShowDetailInfo.value = false
    isShowDetailInfoBtn.value = false
    // 例如：清除高亮、重置状态等
    resetHighlight()
  })
}
// vue 挂载 Dom 的方法
const mountDomFn = (value) => {
  // vue3 中 creatApp 构造 组件传值
  /**
   * @params pop   是 导入的 vue 组件
   * @params objes 是 子组件中用于接收 当前页面传给 pop 组件的值
   *
   * */
  let app = createApp(
    h(pop, {
      popData: value || '传过去的值是chatGPT',
      onTriggerDetail: function (data) {
        currentFwbh.value = data.data.fwbh
        fetchDetails() // 调用父组件的接口方法
      },
    })
  )
  // 提供一个父元素
  const parent = document.createElement('div')
  //mount方法不再像vue2一样支持未挂载的实例，必须得挂载，即必须得给参数
  const instance = app.use(ElementPlus, { size: 'default' }).mount(parent)
  // 返回
  return instance
}
// 没有范围的时候打开详情
const openDetailFn = (data) => {
  // 移除旧的气泡及其关闭事件
  if (popup.value) {
    popup.value.remove()
    popup.value = null
  }
  resetHighlight()
  currentFwbh.value = data.row.fwbh
  fetchDetails() // 调用父组件的接口方法
}
const fetchDetails = async () => {
  await _getZcList()
  await _getJcList()
  await _getXzList()
  await _getQjList()
  await _getSjList()
  let data = {
    list: { zcList: zcList.value, jcList: jcList.value },
    total: {
      zcTotal: zcTotal.value,
      jcTotal: jcTotal.value,
    },
  }
  if (data) {
    isShowDetailList.value = true
    isShowDetailListBtn.value = true
  }
}
/***********************  左侧搜索 + 列表 + 气泡  end  **************************/

/***********************  详情列表 start  **************************/
const openDetailList = () => {
  isShowDetailList.value = !isShowDetailList.value
}
const isShowDetailListBtn = ref(false) // 是否显示详情列表按钮
const isShowDetailList = ref(false) // 是否显示详情列表
const detailList = ref(null) // 详情列表dom
// 详情列表
const zcList = ref([])
const jcList = ref([])
const xzList = ref([])
const qjList = ref([])
const sjList = ref([])
// 详情总数
const zcTotal = ref(0)
const jcTotal = ref(0)
const xzTotal = ref(0)
const qjTotal = ref(0)
const sjTotal = ref(0)
// 详情列表
const _getZcList = async () => {
  let params = {
    pageindex: detailList.value.zcCurrentPage,
    limit: detailList.value.zcCurrentSize,
    text: currentFwbh.value, //房屋编号11010500000640
    yhly: 1,
  }

  let res = await getZcList(params)
  if (res?.data?.data?.items) {
    let list = res?.data?.data?.items
    list.forEach((item, index) => {
      item.index = ++index
    })
    zcList.value = list
    zcTotal.value = res.data?.data?.total
  }
}
const _getJcList = async () => {
  let params = {
    pageIndex: detailList.value.jcCurrentPage,
    limit: detailList.value.jcCurrentSize,
    text: currentFwbh.value, //房屋编号11010500000640
    yhly: 2,
  }
  let res = await getJcList(params)
  if (res?.data?.data?.items) {
    let list = res?.data?.data?.items
    list.forEach((item, index) => {
      item.index = ++index
    })
    jcList.value = list
    jcTotal.value = res.data?.data?.total
  }
}
const _getXzList = async () => {
  let params = {
    pageIndex: detailList.value.xzCurrentPage,
    limit: detailList.value.xzCurrentSize,
    text: currentFwbh.value,
    jcly: 4,
  }

  let res = await getXzList(params)
  if (res?.data?.data?.items) {
    let list = res?.data?.data?.items
    list.forEach((item, index) => {
      item.index = ++index
    })
    xzList.value = list
    xzTotal.value = res.data?.data?.total
  }
}
const _getQjList = async () => {
  let params = {
    pageIndex: detailList.value.qjCurrentPage,
    limit: detailList.value.qjCurrentSize,
    text: currentFwbh.value,
    jcly: 3,
  }

  let res = await getQjList(params)
  if (res?.data?.data?.items) {
    let list = res?.data?.data?.items
    list.forEach((item, index) => {
      item.index = ++index
    })
    qjList.value = list
    qjTotal.value = res.data?.data?.total
  }
}
const _getSjList = async () => {
  let params = {
    pageIndex: detailList.value.sjCurrentPage,
    limit: detailList.value.sjCurrentSize,
    text: currentFwbh.value,
    jcly: 2,
  }

  let res = await getSjList(params)
  if (res?.data?.data?.items) {
    let list = res?.data?.data?.items
    list.forEach((item, index) => {
      item.index = ++index
    })
    sjList.value = list
    sjTotal.value = res.data?.data?.total
  }
}
/***********************  详情列表 end  **************************/

/***********************  详情内容 start  **************************/
const openDetailInfo = () => {
  isShowDetailInfo.value = !isShowDetailInfo.value
}
const isShowDetailInfoBtn = ref(false) // 是否显示详情按钮
const isShowDetailInfo = ref(false) // 是否显示详情
// 详情内容
const houseInfo = ref({})
const yhInfo = ref({})
// 当前显示哪个详情记录
const currentTab = ref('自查记录')
// 详情内容
const _getZcInfo = async (val) => {
  let params = {
    id: val.row.id,
  }
  let res = await getZcInfo(params)
  houseInfo.value = {}
  yhInfo.value = {}
  if (res?.data?.data?.zmPcBase) {
    houseInfo.value = res?.data?.data?.zmPcBase
    yhInfo.value = res?.data?.data?.zmPcYh
    if (houseInfo.value || yhInfo.value) {
      currentTab.value = '自查记录'
      isShowDetailInfo.value = true
      isShowDetailInfoBtn.value = true
    }
  }
}
const _getJcInfo = async (val) => {
  let params = {
    id: val.row.id,
  }
  let res = await getJcInfo(params)
  houseInfo.value = {}
  yhInfo.value = {}
  if (res?.data?.data?.zmPcBase) {
    houseInfo.value = res?.data?.data?.zmPcBase
    yhInfo.value = res?.data?.data?.zmPcYh
    if (houseInfo.value || yhInfo.value) {
      currentTab.value = '检查记录'
      isShowDetailInfo.value = true
      isShowDetailInfoBtn.value = true
    }
  }
}
const _getXzInfo = async (val) => {
  let params = {
    id: val.row.id,
  }
  let res = await getXzInfo(params)
  houseInfo.value = {}
  yhInfo.value = {}
  if (res?.data?.data?.zmPcBase) {
    houseInfo.value = res?.data?.data?.zmPcBase
    yhInfo.value = res?.data?.data?.zmPcYh
    if (houseInfo.value || yhInfo.value) {
      currentTab.value = '乡镇核验记录'
      isShowDetailInfo.value = true
      isShowDetailInfoBtn.value = true
    }
  }
}
const _getQjInfo = async (val) => {
  let params = {
    id: val.row.id,
  }
  let res = await getQjInfo(params)
  houseInfo.value = {}
  yhInfo.value = {}
  if (res?.data?.data?.zmPcBase) {
    houseInfo.value = res?.data?.data?.zmPcBase
    yhInfo.value = res?.data?.data?.zmPcYh
    if (houseInfo.value || yhInfo.value) {
      currentTab.value = '区级核验记录'
      isShowDetailInfo.value = true
      isShowDetailInfoBtn.value = true
    }
  }
}
const _getSjInfo = async (val) => {
  let params = {
    id: val.row.id,
  }
  let res = await getSjInfo(params)
  houseInfo.value = {}
  yhInfo.value = {}
  if (res?.data?.data?.zmPcBase) {
    houseInfo.value = res?.data?.data?.zmPcBase
    yhInfo.value = res?.data?.data?.zmPcYh
    if (houseInfo.value || yhInfo.value) {
      currentTab.value = '市级核验记录'
      isShowDetailInfo.value = true
      isShowDetailInfoBtn.value = true
    }
  }
}
/***********************  详情内容 end  **************************/

/***********************  地图 start  **************************/
const map = ref(null) // 地图实例
const center = ref([116.41995, 40.18994]) // 地图中心点
const indexMap = ref(null) // 地图容器
const fullscreenControl = ref(null) // 全屏控件
const currentFwbh = ref('') //  当前房屋编号

// 初始化地图
const initMap = () => {
  if (map.value) {
    // clearVectorLayerFn()
    // loadVectorLayerFn()
    // clearBeiJingCityFn();
    // loadBeiJingCityFn();
    // flyTo()
    // map.value.on('load', () => {
    //   loadBeiJingCityFn();
    //   flyTo();
    // });
  } else {
    mapboxgl.accessToken =
      'pk.eyJ1IjoibHVrYXNtYXJ0aW5lbGxpIiwiYSI6ImNpem85dmhwazAyajIyd284dGxhN2VxYnYifQ.HQCmyhEXZUTz3S98FMrVAQ'
    map.value = new mapboxgl.Map({
      container: indexMap.value,
      style: {
        version: 8,
        sources: {
          // 影像地图的源
          'tian-satellite-img': {
            type: 'raster',
            tiles: [
              'http://t0.tianditu.gov.cn/img_w/wmts?tk=1883a2da124fe27b3c281f9d65356e82&SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&FORMAT=tiles',
              // "http://t4.tianditu.gov.cn/vec_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=vec&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILECOL={x}&TILEROW={y}&TILEMATRIX={z}&tk=1883a2da124fe27b3c281f9d65356e82",
            ],
            tileSize: 256,
            minzoom: 0,
            maxzoom: 18,
          },
          // 影像地图的源--地名--源
          'tian-satellite-img-placeName': {
            type: 'raster',
            tiles: [
              'http://t0.tianditu.gov.cn/cia_w/wmts?tk=1883a2da124fe27b3c281f9d65356e82&SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cia&STYLE=default&TILEMATRIXSET=w&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&FORMAT=tiles',
              // "http://t1.tianditu.gov.cn/cva_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cva&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILECOL={x}&TILEROW={y}&TILEMATRIX={z}&tk=1883a2da124fe27b3c281f9d65356e82",
            ],
            tileSize: 256,
            minzoom: 0,
            maxzoom: 18,
          },
          // 矢量地图的源
          'tian-satellite-vector': {
            type: 'raster',
            tiles: [
              // "http://t0.tianditu.gov.cn/img_w/wmts?tk=1883a2da124fe27b3c281f9d65356e82&SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&FORMAT=tiles",
              'http://t4.tianditu.gov.cn/vec_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=vec&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILECOL={x}&TILEROW={y}&TILEMATRIX={z}&tk=1883a2da124fe27b3c281f9d65356e82',
            ],
            tileSize: 256,
            minzoom: 0,
            maxzoom: 18,
          },
          // 矢量地图的源--地名--源
          'tian-satellite-vector-placeName': {
            type: 'raster',
            tiles: [
              // "http://t0.tianditu.gov.cn/cia_w/wmts?tk=1883a2da124fe27b3c281f9d65356e82&SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cia&STYLE=default&TILEMATRIXSET=w&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&FORMAT=tiles",
              'http://t1.tianditu.gov.cn/cva_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cva&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILECOL={x}&TILEROW={y}&TILEMATRIX={z}&tk=1883a2da124fe27b3c281f9d65356e82',
            ],
            tileSize: 256,
            minzoom: 0,
            maxzoom: 18,
          },
        },
        layers: [
          {
            id: 'tian-satellite-img',
            type: 'raster',
            source: 'tian-satellite-img',
            layout: {
              visibility: 'none',
            },
            minzoom: 0,
            maxzoom: 22,
          },
          // 影像地图地名--图层
          {
            id: 'tian-satellite-img-layers',
            type: 'raster',
            source: 'tian-satellite-img-placeName',
            layout: {
              visibility: 'none',
            },
            minzoom: 0,
            maxzoom: 22,
          },
          {
            id: 'tian-satellite-vector',
            type: 'raster',
            source: 'tian-satellite-vector',
            layout: {
              visibility: 'none',
            },
            minzoom: 0,
            maxzoom: 22,
          },
          // 影像地图地名--图层
          {
            id: 'tian-satellite-vector-placeName',
            type: 'raster',
            source: 'tian-satellite-vector-placeName',
            layout: {
              visibility: 'none',
            },
            minzoom: 0,
            maxzoom: 22,
          },
        ],
        // 配置天地图的字体
        glyphs: 'mapbox://fonts/mapbox/{fontstack}/{range}.pbf',
      },
      center: center.value,
      zoom: 8,
    })
    // map.value.resize();
    map.value.on('load', (e) => {
      // 设置天气雾化
      map.value.setFog({})
      // 加载影像地图
      map.value.setLayoutProperty('tian-satellite-img', 'visibility', 'visible')
      // 加载影像地图地名
      map.value.setLayoutProperty(
        'tian-satellite-img-layers',
        'visibility',
        'visible'
      )
      // // 全屏控件
      // fullscreenControl.value = new mapboxgl.FullscreenControl()
      // map.value.addControl(fullscreenControl.value, 'top-right')
      // 加载图斑
      const vectorSource = createVectorSource()
      clearVectorLayerFn()
      // 使用新的数据源加载新的图层
      loadVectorLayerFn1(vectorSource)
      // 清除北京矢量数据
      clearBeiJingCityFn
      // 加载北京矢量数据
      loadBeiJingCityFn()
      // 点击 瓦片矢量数据
      map.value.on('click', 'vectorLayer', async (e) => {
        e.preventDefault()
        let id = e.features[0].properties.fwbh
        currentId.value = id
        // 当前图斑高亮
        map.value.setPaintProperty('vectorLayer', 'fill-outline-color', [
          'case',
          ['==', ['get', 'fwbh'], id],
          'red',
          'rgb(255,255,0)',
        ])
        map.value.setPaintProperty('vectorLayer', 'fill-color', [
          'case',
          ['==', ['get', 'fwbh'], id],
          'red',
          // ["get", "fill-color"],
          'transparent',
        ])
        // 获取气泡数据
        let data = e.features[0].properties
        // console.log('@data======', data)
        // console.log('@ e.features[0]====', e.features[0])
        if (popShowData.value) {
          popShowData.value = {}
          popShowData.value = data
          flyCoordinates.value = [data.villagelongitude, data.villagelatitude]
          if (popup.value) {
            popup.value.remove()
            popup.value = null
          }
          initPopup()
          initLight()
        }
      })
    })
    setTimeout(() => {
      // loadVectorLayerFn()
      // flyTo()
    }, 20)
  }
}
// 清除瓦片矢量数据
const clearVectorLayerFn = () => {
  if (map.value && map.value.getLayer('vectorLayer')) {
    map.value.removeLayer('vectorLayer')
  }
  if (map.value && map.value.getSource('vectorSource')) {
    map.value.removeSource('vectorSource')
  }
  // console.log("清除方法执行了");
}
// 创建矢量瓦片
const createVectorSource = () => {
  return {
    type: 'vector',
    tiles: [`${baseUrl}api/v1/houses/mapbox/vector/tiles_q?x={x}&y={y}&z={z}`],
    tileSize: 512,
    minzoom: 0,
    maxzoom: 18,
  }
}
// 加载所有的 矢量瓦片 数据
const loadVectorLayerFn1 = (vectorSource) => {
  // 瓦片矢量数据的源
  map.value.addSource('vectorSource', vectorSource)
  // console.log("点击搜索执行=======加载瓦片矢量数据");
  // 2.加载瓦片矢量数据图层
  map.value.addLayer({
    id: 'vectorLayer',
    'source-layer': 'ffpolygon',
    type: 'fill',
    source: 'vectorSource',
    layout: {
      visibility: 'visible',
    },
    minzoom: 0,
    maxzoom: 22,
    paint: {
      'fill-color': 'transparent',
      'fill-outline-color': 'rgb(255,255,0)',
    },
  })
}
const loadBeiJingCityFn = async () => {
  let code = '110000'
  if (formInline.xzqdm === '') {
    code = '110000'
  } else {
    code = formInline.xzqdm
  }
  const geojson = await fetchGeoJSONData()
  if (geojson) {
    let data1 = JSON.parse(geojson)
    map.value.addSource('beiJingSource', {
      type: 'geojson',
      // https://geo.datav.aliyun.com/areas_v3/bound/110106.json
      // data: `https://geo.datav.aliyun.com/areas_v3/bound/${code}.json`,
      data: data1,
    })
  }

  map.value.addLayer({
    id: 'beiJingLayer',
    type: 'line',
    source: 'beiJingSource',
    layout: {},
    paint: {
      'line-color': '#0000ff', // 边界线颜色
      'line-width': 2, // 边界线宽度
      'line-opacity': 0.8, // 边界线透明度
    },
  })
}
const clearBeiJingCityFn = () => {
  if (map.value && map.value.getLayer('beiJingLayer')) {
    map.value.removeLayer('beiJingLayer')
  }
  if (map.value && map.value.getSource('beiJingSource')) {
    map.value.removeSource('beiJingSource')
  }
}
// 切换地图底图
const mapSwitch = (type) => {
  if (type === 'vec') {
    map.value.setLayoutProperty('tian-satellite-img', 'visibility', 'none')
    // 加载影像地图地名
    map.value.setLayoutProperty(
      'tian-satellite-img-layers',
      'visibility',
      'none'
    )
    map.value.setLayoutProperty(
      'tian-satellite-vector',
      'visibility',
      'visible'
    )
    // 加载影像地图地名
    map.value.setLayoutProperty(
      'tian-satellite-vector-placeName',
      'visibility',
      'visible'
    )
  } else if (type === 'img') {
    map.value.setLayoutProperty('tian-satellite-img', 'visibility', 'visible')
    // 加载影像地图地名
    map.value.setLayoutProperty(
      'tian-satellite-img-layers',
      'visibility',
      'visible'
    )
    map.value.setLayoutProperty('tian-satellite-vector', 'visibility', 'none')
    // 加载影像地图地名
    map.value.setLayoutProperty(
      'tian-satellite-vector-placeName',
      'visibility',
      'none'
    )
  } else {
    map.value.setLayoutProperty('tian-satellite-img', 'visibility', 'none')
    // 加载影像地图地名
    map.value.setLayoutProperty(
      'tian-satellite-img-layers',
      'visibility',
      'visible'
    )
    map.value.setLayoutProperty('tian-satellite-vector', 'visibility', 'none')
    // 加载影像地图地名
    map.value.setLayoutProperty(
      'tian-satellite-vector-placeName',
      'visibility',
      'none'
    )
  }
}
// 返回
const backFn = ()=>{
  router.push({
    path: '/index',
  })
}
/***********************  地图  end  **************************/
// watch()
onMounted(() => {
  getSearchParams()
  _xzqList()
  initMap()
  setTimeout(() => map.value.resize(), 100) // 延时调整
})
const getSearchParams = async () => {
  formInline.xzqdm = route.query.xzqdm || '110000'
  fourRange()
  isShowSearch.value = true
  getTbList()
}
</script>

<style lang="scss" scoped>
/* 确保地图充满整个屏幕 */
.map-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
  #indexMap {
    width: 100%;
    height: 100%; /* 或者其他合适的高度 */
    ::v-deep .mapboxgl-canvas {
      // width: 100%;
      // height: 100%;
    }
    ::v-deep .mapboxgl-control-container {
      .mapboxgl-ctrl-bottom-left {
        .mapboxgl-ctrl {
          .mapboxgl-ctrl-logo {
            display: none;
          }
        }
      }
      .mapboxgl-ctrl-bottom-right {
        .mapboxgl-ctrl-attrib-inner {
          display: none;
        }
        .mapboxgl-compact {
          display: none;
        }
      }
    }
    // 弹框的宽度
    ::v-deep .mapboxgl-popup {
      .mapboxgl-popup-content {
        width: 250px;
        height: auto;
        background-color: rgba(91, 93, 179, 0.8);
        .mapboxgl-popup-close-button {
          color: #fff;
        }
      }
    }
  }
  // 搜索按钮
  .search-btn {
    position: absolute;
    width: 3rem;
    height: 3rem;
    top: 1rem;
    left: 1rem;
    z-index: 999;
  }
  // 搜索内容
  .search-form-container {
    // border: 1px solid red;
    position: absolute;
    top: 1rem;
    left: 5.5rem;
    z-index: 999;
    padding: 1rem;
    width: 64rem;
    height: auto;
    display: flex;
    flex-direction: row;
    align-items: center;

    background-color: rgba(91, 93, 179, 0.8);
    .search-form {
      ::v-deep .el-form-item {
        margin-right: 1rem;
        margin-bottom: 0rem;
      }
      ::v-deep .el-input__wrapper {
        background-color: rgba(91, 93, 179, 0.8);
      }
      ::v-deep .el-select .el-input__inner {
        width: 13.5rem;
        color: #fff;
      }
      ::v-deep .el-input__inner {
        width: 18.5rem;
        color: #fff;
      }
      ::v-deep .el-form-item__label {
        width: 6rem;
        color: #fff;
      }
      ::v-deep .el-radio-group {
        width: 18rem;
        display: flex;
        justify-content: space-between;
        .el-radio {
          width: 8rem;
          margin-right: 0;
          color: #fff;
        }
      }
    }
    .search-action {
      display: flex;
      flex-direction: row;
      align-items: center;
      .action-btn {
        text-align: center;
      }
    }
  }
  // 搜索列表--按钮
  .search-list-btn {
    position: absolute;
    display: flex;
    width: 3rem;
    justify-content: center;
    align-items: center;
    top: 5rem;
    left: 1rem;
    z-index: 999;
  }
  // 详情列表--按钮
  .detail-list-btn {
    position: absolute;
    display: flex;
    width: 3rem;
    justify-content: center;
    align-items: center;
    top: 1rem;
    right: 5rem;
    z-index: 999;
  }
  // 详情--按钮
  .detail-info-btn {
    position: absolute;
    display: flex;
    width: 3rem;
    justify-content: center;
    align-items: center;
    top: 1rem;
    right: 10rem;
    z-index: 999;
  }
  // 返回
  .detail-back-btn{
    position: absolute;
    display: flex;
    width: 3rem;
    justify-content: center;
    align-items: center;
    top: 0.5rem;
    right: 0.5rem;
    z-index: 999;
  }
  // 右侧 切换地图
  .action {
    position: absolute;
    display: flex;
    flex-direction: column;
    align-items: flex-end;
    bottom: 10px;
    right: 10px;
    user-select: none;
    // 切换底图按钮
    .el-dropdown-link {
      background-color: #fff;
      width: 74px;
      height: 30px;
      line-height: 30px;
      border-radius: 5px;
    }
    .el-dropdown-link:hover {
      background-color: #edecec;
      cursor: pointer;
    }
  }
}
</style>
<!-- 选择每页多少条的下拉框列表样式 必须得这么加 -->
<style lang="scss">
.el-select-dropdown {
  background-color: rgba(91, 93, 179, 1); /* 设置下拉框背景颜色 */
  color: #fff; /* 设置列表项字体颜色 */
  .el-select-dropdown__item {
    color: #fff; /* 设置列表项字体颜色 */
  }
  .el-select-dropdown__item.hover,
  .el-select-dropdown__item:hover {
    background-color: #169cdc;
    color: #fff;
  }
}
</style>
